package com.gmj.controller;


import com.gmj.entity.Document;
import com.gmj.entity.Student;
import com.gmj.entity.StudentWorkhome;
import com.gmj.entity.Teacher;
import com.gmj.service.IDocumentService;
import com.gmj.service.IStudentService;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author gmj
 * @since 2022-01-29
 */
@RestController
@RequestMapping("/document")
public class DocumentController {
    @Autowired
    private IDocumentService ds;
    @GetMapping("/selectAll")
    public List<Document> selectAll(){
        return ds.list();
    }
    @PostMapping("/add")
    public void add(@RequestBody Document document){
        document.setSubmitTime(LocalDateTime.now());
        ds.save(document);
    }

    @DeleteMapping("/delete/{id}")
    public void delete(@PathVariable("id") int id){
        ds.removeById(id);
    }

    @Value("${attachPath}")
    private String path;
    @PostMapping("/uploadAttach")
    public String uploadAttach(MultipartFile attach) throws IOException {
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        String oldName=attach.getOriginalFilename();//获取到上传的文件的原始文件名
        String newName = UUID.randomUUID().toString()+oldName;
        attach.transferTo(new File(path,newName));
        return newName;
    }
    @RequestMapping("/download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        //1.通过文件名转换为文件
        File sourceFile=new File(path+fileName);
        //2.设置响应格式和文件的名字
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
        //3.把文件放入到response里面。
        FileUtils.copyFile(sourceFile,response.getOutputStream());
    }
}

